!(function ($) {

    "use strict";

    var templates = {
        panel: '<div class="box_tc_s"><ul class="directory-panel"><li><a href="#" data-handle="add" iconCls="fa fa-plus fa-lg" plain="true">新增</a></li></ul></div>',
        rowEdit:'<li data-id="{{id}}" data-type="edit">' +
            '<label>编码：<input type="text" style="width: 80px" class="easyui-validatebox hydra-input-width" name="dirCode" value="{{dirCode}}"/></label>' +
            '<label>值：<input type="text" style="width: 80px"  class="easyui-validatebox hydra-input-width" name="dirValue" value="{{dirValue}}"/></label></label>' +
            '<span><a href="#" data-handle="save" iconCls="icon-save" plain="true">保存</a><a href="#" data-handle="cancel" plain="true">取消</a></span></li>',
        rowDetail:'<li data-id="{{id}}" data-type="detail"><span class="operate" data-status="normal">' +
            '<a href="#" data-handle="edit" iconCls="e-icon fa fa-edit fa-lg" plain="true">编辑</a><a href="#" data-handle="del"  iconCls="e-icon fa fa-trash fa-lg" plain="true">删除</a></span>' +
            '<span class="dir-info"><span data-name="dirValue">{{dirValue}}</span><span data-name="dirCode">({{dirCode}})</span></span></li>'
    };

    function create(target){
        var state = $.data(target, 'directory');
        var opts = state.options;
        var comp = new Component(opts);
        $(target).on("click", function(){
            comp.openDialog();
        })
    }


    function Component(op) {
        var that = this;
        this.opt = op;
        this.wedget = $(templates.panel).appendTo("body");
        this.wedget.find("[data-handle=add]").linkbutton({onClick:function(){
            events.onClickAddBtn.call(this, that);
        }});
        this.wedget.dialog({
            width: 430,
            height: 400,
            closed: true,
            modal: true,
            title: this.opt.title,
            loadingMessage: '',
            buttons: [
                {
                    text: '关闭',
                    handler: function () {
                        that.wedget.dialog("close");
                    }
                }
            ]
        });
        this.fillRow(this.opt.getUrl, this.opt.params);
    }

    Component.prototype.openDialog = function(){
        this.wedget.dialog("open");
    };

    Component.prototype.editRow = function (row, insertMethod) {
        var that = this;
        var _row = Mustache.render(templates.rowEdit, row);
        var $row = insertMethod(_row);
        $row.data("dataRow", row);
        if(!this.opt.showCode){
            $row.find("[name=dirCode]").parent().remove();
        }
        $row.find("[data-handle]").linkbutton({
            onClick:function(){
                var target = $(this).attr("data-handle");
                switch (target) {
                    case "save":
                        events.onClickSaveBtn.call(this, that);
                        break;
                    case "cancel":
                        events.onClickCancelBtn.call(this, that);
                        break;
                    default:
                        break;
                }
            }
        })
    };

    Component.prototype.renderRow = function(row, insertMethod){
        var that = this;
        var _row = Mustache.render(templates.rowDetail, row);
        var $row = insertMethod(_row);
        $row.data("dataRow", row);
        if(!this.opt.showCode){
            $row.find("[data-name=dirCode]").remove();
        }
        $row.find("[data-handle]").linkbutton({
            onClick:function(){
                var target = $(this).attr("data-handle");
                switch (target) {
                    case "edit":
                        events.onClickEditBtn.call(this, that);
                        break;
                    case "del":
                        events.onClickDelBtn.call(this, that);
                        break;
                    default:
                        break;
                }
            }
        })
    };

    Component.prototype.fillRow = function (url, params) {
        var that = this;
        $.getJSON(url, params, function (data) {
            if($.isPlainObject(data) && data.error){
                $.messager.alert('信息',data.msg, 'error');
            }else{
                for (var i = data.length-1; i >= 0; i--) {
                    that.renderRow(data[i], function(row){
                        return $(row).prependTo(that.wedget.find("ul"))
                    });
                }
            }
        }, "JSON")
    };

    var events = {
        onClickAddBtn: function (context) {
            var $this = $(this);
            var row = context.editRow({}, function(row){
                return $(row).insertBefore($this.parents("li"));
            });
        },
        onClickEditBtn: function (context) {
            var current = $(this).parents("li").hide();
            var row = current.data("dataRow");
            context.editRow(row, function(temp){
                return $(temp).insertBefore(current);
            });
            current.remove();
        },
        onClickDelBtn: function (context) {
            var $this = $(this);
            $.messager.confirm("信息", "是否确定需要删除该数据字典项？", function(arg){
               if(arg){
                   var current = $this.parents("li");
                   $.post(context.opt.delUrl, {id: current.attr("data-id")}, function(data){
                       if($.isPlainObject(data) && data.error){
                           $.messager.alert('信息',
                               data.msg, 'error');
                       }else{
                           current.remove();
                           context.opt.delSuccess.call(context);
                       }
                   }, "JSON")
               }
            });
        },
        onClickCancelBtn: function (context) {
            var p = $(this).parents("li").hide();
            var row = p.data("dataRow");
            if($.isPlainObject(row) && !$.isEmptyObject(row)){
                context.renderRow(row, function(temp){
                    return $(temp).insertBefore(p);
                });
            }
            p.remove();
        },
        onClickSaveBtn: function (context) {
            function post(row, postAfter){
                $.post(context.opt.postUrl, row, function(data){
                    if($.utils.isError(data)){
                        $.messager.alert('信息',
                            data.msg, 'error');
                    }else{
                        postAfter(context, data);
                        context.opt.saveSuccess.call(context);
                    }
                })
            }
            var p = $(this).parents("li");
            var row = {
                id: p.attr("data-id"),
                dirValue:p.find("[name=dirValue]").val(),
                dirCode:p.find("[name=dirCode]").val()
            };

            if(row.dirValue.length  > 50){
                $.messager.alert('提示', '数据长度不能大于50','info');
                return ;
            }else if(row.dirValue == undefined || row.dirValue.length == 0){
                $.messager.alert('提示', '值不能为空!','info');
                return ;
            }

            if(!validator(row.dirValue)){
                $.messager.alert('提示', '不能含有特殊字符!','info');
                return ;
            }

            if(!row.id){delete row.id;}
            post(row, function(context, reback){
                context.renderRow(reback, function(temp){
                    var tp = $(temp).insertBefore(p);
                    p.remove();
                    return tp;
                });
            });
        }
    };

    $.fn.directory = function(options, param){
        if (typeof options == 'string'){
            var method = $.fn.directory.methods[options];
            if (method){
                return method(this, param);
            }
        }

        options = options || {};
        return this.each(function(){
            var state = $.data(this, 'directory');
            if (state){
                $.extend(state.options, options);
            } else {
                state = $.data(this, 'directory', {
                    options: $.extend({}, $.fn.directory.defaults, options)
                });
            }
            create(this);
        });
    };

    $.fn.directory.methods = {

    };

    $.fn.directory.defaults = {
        getUrl:"",
        postUrl:"",
        params:{},
        delUrl:"",
        showCode:false,
        //event
        delSuccess: $.noop,
        saveSuccess: $.noop
    };

    function validator(test) {
        return /^[\u4e00-\u9fa5\da-zA-Z\-\_]+$/gi.test(test);
    }

})(window.jQuery);